package com.ruyuan.seckilling.render.async.listener;

import com.ruyuan.seckilling.render.async.BaseRenderPageListener;
import com.ruyuan.seckilling.render.async.PageRenderContext;
import com.ruyuan.seckilling.render.async.event.Event04RenderPage;
import com.ruyuan.starter.async.anno.Channel;
import com.ruyuan.starter.async.event.BaseEvent;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import java.util.HashMap;
import java.util.Map;

import static com.ruyuan.seckilling.common.ChannelKey.CHANNEL_04_RENDER_PAGE;
import static com.ruyuan.seckilling.common.ChannelKey.CHANNEL_05_UPLOAD_STATIC_PAGE;
import static com.ruyuan.seckilling.render.async.PageRenderEventHolder.EVENT_05;

/**
 * @author zhonghuashishan
 */
@Slf4j
@Component
@Channel(CHANNEL_04_RENDER_PAGE)
public class Event04Listener extends BaseRenderPageListener<Event04RenderPage> {

    public boolean accept(BaseEvent event) {
        return event instanceof Event04RenderPage;
    }

    /**
     * 4、模板+数据渲染页面
     */
    @Override
    protected void doThisStep(Event04RenderPage event, PageRenderContext context) {

        Runnable task = () -> {
            Map<String, Object> mapData = new HashMap<>(1);
            mapData.put("data", context.getAggrData());
            String staticPageFile;
            try {
                String key = "template";
                Configuration configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
                StringTemplateLoader stringTemplateLoader = new StringTemplateLoader();
                stringTemplateLoader.putTemplate(key, context.getTemplateContent());
                configuration.setTemplateLoader(stringTemplateLoader);
                Template template = configuration.getTemplate(key);
                staticPageFile = FreeMarkerTemplateUtils.processTemplateIntoString(template, mapData);
            } catch (Exception e) {
                context.getPageLog().setSuccess(false);
                context.getPageLog().setInfo("模板+数据渲染页面时出现问题");
                context.setShouldSkip(true);
                return;
            }

            context.setStaticPageContent(staticPageFile);
            bossEventBus.publish(CHANNEL_05_UPLOAD_STATIC_PAGE, EVENT_05, context);
            log.info("第4步，渲染页面");
        };

        executorService.execute(CHANNEL_04_RENDER_PAGE, task);
    }
}
